#!/bin/bash 
#################################################################################
# RoboFight server start script							#
# Starts the RoboFight server for unix-like systems                             #
#################################################################################	
function print_help {
echo "The commandline options are:
startGameServer [-port PORT] [-drop] [-host IP] - starts the server [on a specific port] [dropping the database] [on a specific host ip]
stopGameServer - stops the currently running server
startWebServer - starts jetty on port 80
stopWebServer - stops jetty"
}
get_Pid () 
{
  PID=$(ps ax | grep robofight.jar | grep -v grep | awk '{ print $1 }')
}

function print_error {
	echo "Use help option to get help about command line options"
	exit 1
}
function start_WebServer {
	cd jetty
	bin/jetty.sh start
}
function stop_WebServer
{
	cd jetty
	bin/jetty.sh stop
}
function start_GameServer
{
	get_Pid
	if [ -z $PID ]; then
		java -Djava.security.policy=etc/sec.pol -jar bin/robofight.jar -confDir etc ${@} &
	else
		echo "Server is already running!"
	fi
}
function stop_GameServer
{
	get_Pid 

 if [ ! -z $PID ] ; then
      kill $PID
      sleep 5
      get_Pid
      if [ ! -z $PID ] ; then
        kill -9 $PID
        sleep 5
      fi
 else 
	echo "Server process wasn't found"
 fi
}
#make sure we are in the right dir for further operations
x=`dirname "$0"`;
cd ${x};
# check for cmd line arguments
case $1 in
	 help)
	print_help
;;
       	startGameServer)
	start_GameServer ${@:2}
;;
	stopGameServer)
	stop_GameServer
;;
	startWebServer)
	start_WebServer
;;
	stopWebServer)
	stop_WebServer
;;
	*)
	print_error
;;
esac
